package com.zyq.shoppinglist;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Zyq On 2019/4/3 10:52
 */
public class AddAndSub extends LinearLayout {
    private View rootview;
    private TextView sub;
    private TextView number;
    private TextView add;

    public AddAndSub(Context context) {
        this(context, null);
    }

    public AddAndSub(Context context, AttributeSet attrs) {
        this(context, attrs, -1);
    }

    public AddAndSub(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initview(context);
        listener();
    }
    private void listener() {
        //减
        sub.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                sub();
            }
        });

        //加
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
    }


    private void sub() {
        String num = number.getText().toString().trim();
        int numb = Integer.parseInt(num);
        if (numb > 1) {
            numb--;
            setCurrentNum(numb);
        } else {
            Toast.makeText(getContext(), "用户最小数量为1", Toast.LENGTH_SHORT).show();
        }
    }

    private void add() {
        String num = number.getText().toString().trim();
        int numb = Integer.parseInt(num);
        numb++;
        setCurrentNum(numb);
    }

    private void initview(Context context) {
        rootview = View.inflate(context, R.layout.addandsub, this);
        sub = rootview.findViewById(R.id.num_sub);
        number = rootview.findViewById(R.id.number);
        add = rootview.findViewById(R.id.num_add);
        /*number.setText("1");*/
    }

    //设置获取当前数量的方法
    public void setCurrentNum(int num) {
        number.setText("" + num);
        if (onChangNum != null) {
            onChangNum.changeNum(this, num);
        }
    }

    public interface OnChangNum {
        void changeNum(View view, int currentNum);
    }

    private OnChangNum onChangNum;

    public void setOnChangNumListener(OnChangNum onChangNum) {
        this.onChangNum = onChangNum;
    }
}
